package com.aiti.lulian.controller;

import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.DraftsDto;
import com.aiti.lulian.entity.Drafts;
import com.aiti.lulian.service.IDraftsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@Api(tags = "表单草稿控制层")
@RestController
@RequestMapping("/drafts")
public class DraftsController extends WebController<Drafts> {

    @Autowired
    private IDraftsService draftsService;

    @ApiOperation("保存草稿")
    @PostMapping("/save")
    public Message save(@RequestBody DraftsDto dto) {
        Drafts drafts = new Drafts();
        BeanUtils.copyProperties(dto, drafts);
        drafts.setBaseCreateTime(new Date());
        draftsService.save(drafts);
        return Message.success("保存成功");
    }

    @ApiOperation("查询草稿内容")
    @GetMapping("/getDrafts")
    public Message getDrafts(@RequestParam("userId") String userId,
                             @RequestParam("formSource") String formSource) {
        Drafts drafts = draftsService.getOne(new LambdaQueryWrapper<Drafts>().eq(Drafts::getUserId, userId).eq(Drafts::getFormSource, formSource));
        return Message.success(drafts);
    }

    @ApiOperation("清空当前用户指定表单的草稿内容")
    @DeleteMapping("/remove")
    public Message removeDrafts(DraftsDto dto) {
        String userId = dto.getUserId();
        String formSource = dto.getFormSource();
        Drafts drafts = draftsService.getOne(new LambdaQueryWrapper<Drafts>().eq(Drafts::getUserId, userId).eq(Drafts::getFormSource, formSource));
        if (drafts != null) {
            draftsService.removeById(drafts.getBaseId());
        }
        return Message.success();
    }
}
